package com.webside.base.basedao.impl;

import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import com.webside.base.basedao.BaseDao;
import com.webside.base.basedao.MyBatisSql;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;


public class BaseDaoImpl implements BaseDao {

	private static final Logger log = Logger.getLogger(BaseDaoImpl.class);
	
	@Autowired
	private SqlSessionTemplate sqlSession;
	
	/**
	 * 查询列表数据
	 */
	public List selectList(String sqlName, Object obj) {
		return this.sqlSession.selectList(sqlName, obj);
	}

	/**
	 * 查询列表数据
	 */
	public List selectList(String sqlName) {
		return this.sqlSession.selectList(sqlName);
	}

	/**
	 * 查询一条数据
	 * 
	 * @param sqlName
	 * @param obj
	 * @return
	 */
	public Object selectOne(String sqlName, Object obj) {
		return this.sqlSession.selectOne(sqlName, obj);
	}

	/**
	 * 更新数据
	 * 
	 * @param sqlName
	 * @param obj
	 * @return
	 */
	public int update(String sqlName, Object obj){
		return this.sqlSession.update(sqlName, obj);
	}

	/**
	 * 插入一条数据
	 * 
	 * @param sqlName
	 * @param obj
	 * @return
	 */
	public int insert(String sqlName, Object obj) {
		return this.sqlSession.insert(sqlName, obj);
	}

	/**
	 * 删除数据
	 * 
	 * @param sqlName
	 * @param obj
	 * @return
	 */
	public int delete(String sqlName, Object obj) {
		return this.sqlSession.delete(sqlName, obj);
	}
	
	/**
	 * 查询分页数据
	 * 
	 * @param sql
	 * @param parameterObject
	 * @param skipResults
	 * @param maxResults
	 * @return
	 */
	public List getPage(String sql, Object parameterObject, int skipResults,
			int maxResults) {
		log.info("getPage sqlSession="+sqlSession.toString()+" "+sqlSession.hashCode()+" "+sql);
		return this.sqlSession.selectList(sql, parameterObject, new RowBounds(
				skipResults, maxResults));
	}

	public void setAutoCommit(boolean autoCommit) {
		try {
			this.sqlSession.getConnection().setAutoCommit(autoCommit);
		} catch (SQLException e) {
			//e.printStackTrace();
			log.error("", e);
		}
	}

	public void updateBatch(String sqlName, Collection list) {
		setAutoCommit(false);
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Object object = (Object) iterator.next();
			this.sqlSession.update(sqlName, object);
		}
		// this.commit();
	}

	@Override
	public MyBatisSql getMyBatisSql(String id, Object parameterObject) {
		// TODO Auto-generated method stub
		return null;
	}
}
